// 插件管理器
import { join } from 'path'
import fs from 'fs-extra'
import db from './db'

const localPluginKey = `local-plugin`

class PluginMgr {
  plugins: plugin.Plugin[] = []
  rev?: string

  async init() {
    //加载本地插件
    const data = await db.get<plugin.Plugin[]>(localPluginKey)
    this.plugins = data?.data ?? []
    this.rev = data?._rev

    console.log('plugin init', this.plugins, this.rev)

    //测试插件
    this.loadPlugin('/Users/apple/Documents/gocode/src/front/stools-plugin/plugin.json')

    // this.save()
  }

  loadPlugin(pluginJsonPath: string) {
    //检查文件是否存在
    if (!fs.existsSync(pluginJsonPath)) {
      console.log('文件不存在')
      return
    }

    //读取json文件
    const pluginJson = fs.readJSONSync(pluginJsonPath, 'utf-8')
    const plugin = {
      name: 'test-plugin',
      baseDir: join(pluginJsonPath, '..'),
      dev: true,
      config: pluginJson
    } as plugin.Plugin

    plugin.config.logo = 'image://' + join(plugin.baseDir, plugin.config.logo)

    plugin.config.features.forEach((feature) => {
      feature.icon = feature.icon ? 'image://' + join(plugin.baseDir, feature.icon) : undefined
    })

    if (!this.plugins.find((e) => e.name === plugin.name)) {
      this.plugins.push(plugin)
    }

    // console.log('plugins', this.plugins)
  }

  private async save() {
    const ret = await db.put<plugin.Plugin[]>({
      _id: localPluginKey,
      _rev: this.rev,
      data: this.plugins
    })
    this.rev = ret?.rev
    return ret
  }
}

export default new PluginMgr()
